<template>
  <div class="clearfix">
    <a-upload
      :action="upload.url + '/common/upload'"
      @download="download"
      @change="handleChange"
      :headers="upload.headers"
      :file-list="files"
    >
      <a-button>
        <upload-outlined></upload-outlined>
        点击修改文件
      </a-button>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <a :href="previewImage">下载</a>
    </a-modal>
  </div>
</template>
<script>
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
import storage from "store";
import { ACCESS_TOKEN } from "@/store/mutation-types";
export default {
  name: "SysUpload",
  props: {
    value: {
      type: String,
      default: "",
    },
    files: {
      type: Array,
    },
  },
  data() {
    return {
      previewVisible: false,
      previewImage: "",

      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        uploadStatus: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + storage.get(ACCESS_TOKEN) },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API,
      },
    };
  },
  methods: {
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    download(file) {
      return file.url;
    },
    handleChange({ fileList }) {
      this.files = fileList;
      for (let i = 0; i < this.files.length; i++) {
        if (this.files[i].response) {
          this.$emit("input", this.files[i].response.data.url);
        }
      }
    },
  },
};
</script>
<style>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
